//
//  WYHeroController.m
//  Boss
//
//  Created by admin on 2018/8/23.
//  Copyright © 2018年 admin. All rights reserved.
//

#import "WYHeroController.h"
#import <JavaScriptCore/JSContext.h>
#import <JavaScriptCore/JavaScriptCore.h>
#import "UIWebView+TS_JavaScriptContext.h"
#import "WXApi.h"
#import "UIButton+WYColor.h"
@protocol JSHeroObjcDelegate <JSExport>
// AndroidWebView对象调用的JavaScript方法，必须声明！！！
-(void)showShareButton:(NSString *)str;
@end
@interface WYHeroController ()<JSHeroObjcDelegate,TSWebViewDelegate>
@property (nonatomic,strong)UIWebView *webView;
@property (nonatomic,strong)JSContext *context;
@property (nonatomic,strong)UIButton *showOffBtn;
@end

@implementation WYHeroController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
    // Do any additional setup after loading the view.
}
-(void)setupUI
{
    [self wr_setNavBarBackgroundAlpha:0];
    [self wr_setNavBarShadowImageHidden:YES];
    self.webView = [[UIWebView alloc]init];
    self.webView.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
    [self.view addSubview:self.webView];
    self.webView.delegate = self;
    WYUserMessage *userMessage = [WYStoreModule currentUserMessage];
    NSString *urlString =[NSString stringWithFormat:@"%@?userId=%@&type=2",@"https://u.juniuboss.com/hero/hero.html",userMessage.id];
    NSLog(@"%@",urlString);
    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlString]]];
    self.webView.scrollView.bounces = NO;
    UIButton *showOffBtn = [[UIButton alloc]init];
    [self.view addSubview:showOffBtn];
    if (@available(iOS 11.0, *)){
        [self.webView.scrollView setContentInsetAdjustmentBehavior:(UIScrollViewContentInsetAdjustmentNever)];
//        [[UIScrollView appearance] setContentInsetAdjustmentBehavior:UIScrollViewContentInsetAdjustmentNever];
    }
   
    
    
//    [showOffBtn mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.mas_equalTo(50);
//        make.right.mas_equalTo(-50);
//        make.bottom.mas_equalTo(-20);
//        make.height.mas_equalTo(50);
//    }];
    
    
    showOffBtn.frame = CGRectMake(50, kScreenHeight-70, kScreenWidth-100, 50);
    [showOffBtn setCornerRadius:25.f];
  
    [showOffBtn.layer addSublayer:[UIButton setGradualChangingColor:showOffBtn fromColor:@"#FFE53F" toColor:@"#FFAF0A"]];
    self.showOffBtn = showOffBtn;
    [showOffBtn setTitle:@"炫耀一下" forState:UIControlStateNormal];
    showOffBtn.titleLabel.font = [UIFont systemFontOfSize:18];
    [showOffBtn setTitleColor:[UIColor blackColor] forState:(UIControlStateNormal)];
    showOffBtn.hidden = YES;
    [showOffBtn addTarget:self action:@selector(showOffAction:) forControlEvents:(UIControlEventTouchUpInside)];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"通用_返回白"] style:(UIBarButtonItemStyleDone) target:self action:@selector(returnToTop)];
    
}
-(void)returnToTop
{
    if ([self.webView canGoBack]) {
        self.showOffBtn.hidden = YES;
        [self.webView goBack];
    }else{
        [self.navigationController popViewControllerAnimated:YES];
    }
    
    
    
    
}
-(void)showOffAction:(UIButton *)btn
{
    
    WXMediaMessage *message = [WXMediaMessage message];
    //[message setThumbImage:[UIImage imageNamed:@"example"]];
    WXImageObject *imageObject = [WXImageObject object];
    UIImage *image = [self convertViewToImage:self.webView];
    NSData *data = UIImagePNGRepresentation(image);
    imageObject.imageData = data;
    // 多媒体数据对象，可以为WXImageObject，WXMusicObject，WXVideoObject，WXWebpageObject等。
    message.mediaObject = imageObject;
    
    SendMessageToWXReq *req = [[SendMessageToWXReq alloc] init];
    req.bText = NO;
    req.message = message;
    req.scene = WXSceneTimeline;// 分享到朋友圈
    [WXApi sendReq:req];
    
    
    
}

-(UIImage*)convertViewToImage:(UIView*)v{
    
    CGRect rect = v.bounds;
    UIEdgeInsets capInsets = UIEdgeInsetsZero;
    CGFloat scale = [UIScreen mainScreen].scale;
    CGSize boundsSize = self.webView.bounds.size;
    CGFloat boundsWidth = boundsSize.width;
    CGFloat boundsHeight = boundsSize.height;
    
    CGSize contentSize = self.webView.scrollView.contentSize;
    CGFloat contentHeight = contentSize.height;
    //    CGFloat contentWidth = contentSize.width;
    
    CGPoint offset = self.webView.scrollView.contentOffset;
    
    [self.webView.scrollView setContentOffset:CGPointMake(0, 0)];
    
    NSMutableArray *images = [NSMutableArray array];
    while (contentHeight > 0) {
        UIGraphicsBeginImageContextWithOptions(boundsSize, NO, [UIScreen mainScreen].scale);
        [self.webView.layer renderInContext:UIGraphicsGetCurrentContext()];
        UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        [images addObject:image];
        
        CGFloat offsetY = self.webView.scrollView.contentOffset.y;
        [self.webView.scrollView setContentOffset:CGPointMake(0, offsetY + boundsHeight)];
        contentHeight -= boundsHeight;
    }
    
    
    [self.webView.scrollView setContentOffset:offset];
    
    CGSize imageSize = CGSizeMake(contentSize.width * scale,
                                  contentSize.height * scale);
    UIGraphicsBeginImageContext(imageSize);
    [images enumerateObjectsUsingBlock:^(UIImage *image, NSUInteger idx, BOOL *stop) {
        [image drawInRect:CGRectMake(0,
                                     scale * boundsHeight * idx,
                                     scale * boundsWidth,
                                     scale * boundsHeight)];
    }];
    UIImage *fullImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    UIImageView * snapshotView = [[UIImageView alloc]initWithFrame:CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height)];
    
    snapshotView.image = [fullImage resizableImageWithCapInsets:capInsets];
    return snapshotView.image;
}









- (void)webView:(UIWebView *)webView didCreateJavaScriptContext:(JSContext *)ctx
{
    ctx[@"share"] = self;
}
-(void)webViewDidFinishLoad:(UIWebView *)webView
{
    self.context = [self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    self.context [@"share"] = self;
}
-(void)showShareButton:(NSString *)str
{
    
   // NSLog(@"1231321313131313132331232");
    if ([str isEqualToString:@"hide"]) {
        dispatch_async(dispatch_get_main_queue(), ^{
            // UI更新代码
            self.showOffBtn.hidden = YES;
        });
        
    }
    if ([str isEqualToString:@"show"]) {
        dispatch_async(dispatch_get_main_queue(), ^{
            // UI更新代码
             self.showOffBtn.hidden = NO;
        });
        
       
    }
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end
